package com.ssy.jt808.gateway.application.endpoint;

import com.ssy.jt808.protocol.basics.JTMessage;
import com.ssy.jt808.protocol.commons.JT808;
import com.ssy.jt808.protocol.t808.T8001;
import com.ssy.netmc.core.HandlerInterceptor;
import com.ssy.netmc.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangzezhou
 */
public class JTHandlerInterceptor implements HandlerInterceptor<JTMessage>{

  private static final Logger
    log
    = LoggerFactory.getLogger(JTHandlerInterceptor.class.getSimpleName());

  /** 未找到对应的Handle */
  @Override
  public JTMessage notSupported( JTMessage request, Session session ){
    T8001 response = new T8001();
    response.copyIdVersionProtocol(request);
    response.setMessageId(JT808.平台通用应答);
    response.setSerialNo(session.nextSerialNo());

    response.setResponseSerialNo(request.getSerialNo());
    response.setResponseMessageId(request.getMessageId());
    response.setResultCode(T8001.NotSupport);

    log.info("{}\n<<<<-未识别的消息{}\n>>>>-{}", session, request, response);
    return response;
  }


  /** 调用之后，返回值为void的 */
  @Override
  public JTMessage successful( JTMessage request, Session session ){

    T8001 response = new T8001();
    response.copyIdVersionProtocol(request);
    response.setMessageId(JT808.平台通用应答);
    response.setSerialNo(session.nextSerialNo());

    response.setResponseSerialNo(request.getSerialNo());
    response.setResponseMessageId(request.getMessageId());
    response.setResultCode(T8001.Success);

    return response;
  }

  /** 调用之后抛出异常的 */
  @Override
  public JTMessage exceptional( JTMessage request, Session session, Throwable t ){

    T8001 response = new T8001();
    response.copyIdVersionProtocol(request);
    response.setMessageId(JT808.平台通用应答);
    response.setSerialNo(session.nextSerialNo());

    response.setResponseSerialNo(request.getSerialNo());
    response.setResponseMessageId(request.getMessageId());
    response.setResultCode(T8001.Failure);

    log.warn(session + "\n<<<<-" + request + "\n>>>>-" + response + '\n', t);
    return response;
  }

  /** 调用之前 */
  @Override
  public boolean beforeHandle( JTMessage request, Session session ){
    int messageId = request.getMessageId();
    if( messageId == JT808.终端注册 || messageId == JT808.终端鉴权 ){
      return true;
    }

    if( !session.isRegistered() ){
      log.error("{} 未注册的设备<<<<-{}", session, request);
      session.close();
      return false;
    }
    return true;
  }

  /** 调用之后 */
  @Override
  public void afterHandle( JTMessage request, JTMessage response, Session session ){
    if( response != null ){
      response.copyIdVersionProtocol(request);
      response.setSerialNo(session.nextSerialNo());

      if( response.getMessageId() == 0 ){
        response.setMessageId(response.reflectMessageId());
      }
    }
  }
}